package com.zzyy.dtx.order.msg;

import com.alibaba.fastjson.JSON;
import com.zzyy.dtx.commons.enums.MsgEnum;
import com.zzyy.dtx.msg.api.MsgApi;
import com.zzyy.dtx.msg.dto.MsgDTO;
import com.zzyy.dtx.order.dto.OrderDTO;
import com.zzyy.dtx.order.entities.Order;
import com.zzyy.dtx.order.enums.OrderStatusEnum;
import com.zzyy.dtx.order.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @auther zzyy
 * @create 2023-05-21 18:02
 * exchange:msg.exchange
 * routingkey:order.routing.key  ;;
 *
 * mq.msg.exchange=msg.exchange
 * mq.msg.queue.name=order.msg
 * mq.msg.queue.routing.key=order.routing.key
 */
@Component
@Slf4j
@RabbitListener(
        bindings=@QueueBinding(
        value= @Queue(value="${mq.msg.queue.name}",autoDelete="false"),
        exchange=@Exchange(value="${mq.msg.exchange}",type= ExchangeTypes.DIRECT),
        key="${mq.msg.queue.routing.key}")
)
public class MsgListenerHandler {
    @Resource
    private OrderMapper orderMapper;
    @Resource private MsgApi msgApi;

    @RabbitHandler
    public void process(String content){
        System.out.println("#####接收到支付信息:"+content);

        log.info("接收到支付信息:{}",content);
        //对应设计图  第8步骤.处理本地业务tx_order表更新status字段从2=未支付改为3=支付成功
        OrderDTO orderDTO= JSON.parseObject(content, OrderDTO.class);
        Order order=new Order();
        order.setOrderNo(orderDTO.getOrderNo());
        Order orderDBEntity=this.orderMapper.selectOne(order);
        orderDBEntity.setStatus(OrderStatusEnum.PAY_SUCCESS.getCode());
        this.orderMapper.updateByPrimaryKeySelective(orderDBEntity);

        /**
         * 最后删除消息，对应设计图，第9步骤将消息直接删除this.msgApi.deleteMsg(msgDTO);
         *
         * 1 物理删除，直接delete干掉记录
         * 2 逻辑删除，tx_msg表里字段deleted` 默认0不删除，1删除',
         * 3 不做处理，tx_msg表里字段create_time，按照时间最后统一归档后处理
         */
        String msgid= MsgEnum.ORDER.getCode()+"-"+orderDTO.getOrderNo();
        MsgDTO msgDTO=new MsgDTO();
        msgDTO.setMsgId(msgid);

        //this.msgApi.deleteMsg(msgDTO);

        System.out.println("-==========end RabbitHandler");
    }
}
